<?php
/**
 * Created by PhpStorm.
 * User: gyq
 * Date: 2018/11/12
 * Time: 21:15
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\service\Order as OrderService;
use app\api\service\Token as TokenService;
use app\api\validate\IDMustBePositiveInt;
use app\api\validate\OrderPlace;
use app\api\validate\PagingParameter;
use app\api\service\Token;
use app\api\model\Order as OrderModel;
use app\lib\exception\OrderException;

class Order extends BaseController
{
    protected $beforeActionList = [
        'checkExclusiveScope' => ['only' => 'placeOrder'],
        'checkPrimaryScope' => ['only' => 'getDetail,getSummaryByUser']
    ];

    public function getDetail($id)
    {
        (new IDMustBePositiveInt())->goCheck();
        $orderDetail = OrderModel::get($id);
        if (!$orderDetail) {
            throw new OrderException();
        }
        return $orderDetail->hidden(['prepay_id']);
    }

    public function getSummaryByUser($page = 1, $size = 15)
    {
        (new PagingParameter())->goCheck();
        $uid = Token::getTokenUid();
        $orderData = OrderModel::getSummaryByUser($uid, $page, $size);
        if ($orderData->isEmpty()) {
            return [
                'data' => [],
                'current_page' => $orderData->currentPage()];
        }
        $data = $orderData->hidden(['snap_items', 'snap_address', 'prepay_id'])->toArray();
        return [
            'data' => $data,
            'current_page' => $orderData->currentPage()
        ];
    }

    public function placeOrder()
    {
        (new OrderPlace())->goCheck();
//        /a才能得到数组，不然得不到数组
        $product = input('post.products/a');
        $uid = TokenService::getTokenUid();
        $orderService = new OrderService();
        $status = $orderService->place($uid, $product);
        return json($status, 200);
    }
}